package Offer.offer2022;

/**
 * 数值的整数次方
 */
public class Test11 {
    public static void main(String[] args) {
        System.out.println(getBaseExponentResult(10, -3));
    }

    public static double getBaseExponentResult(double base, int exponent) {
        if (isEquals(base, 0.0)) {
            if (exponent < 0) {
                throw new ArithmeticException("can not be divided by zero");
            } else {
                return 0;
            }
        }
        int absExp = exponent;
        if (exponent < 0) {
            absExp = - exponent;
        }
        double result = getUnsignResult2(base, absExp);

        if (exponent < 0) {
            result = 1.0 / result;
        }

        return result;
    }

    private static double getUnsignResult(double base, int absExp) {
        double result = 1.0;
        for (int i = 0; i < absExp; i++) {
            result *= base;
        }
        return result;
    }

    //递归法
    public static double getUnsignResult2(double base, int exponent) {
        if (exponent == 0) {
            return 1;
        }
        if (exponent == 1) {
            return base;
        }

        double result = getUnsignResult2(base, exponent >> 1);
        result = result * result;
        if ((exponent & 1) == 1) {
            result *= base;
        }
        return result;
    }

    private static boolean isEquals(double value1, double value2) {
        return value1 - value2 > -0.0000000001 && value1 - value2 < 0.000000001;
    }
}
